package com.faithnmn.learnenglishbc.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import com.faithnmn.utils.weather.model.Weather;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;

public class Utils {
	public static Bitmap decodeBitmapFromBase64(String encodedImage) {
		byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
		Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
				decodedString.length);
		return decodedByte;
	}
	
	public static Bitmap decodeBitmapFromBase64(String encodedImage,int width,int height) {
		byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
		Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
//		Log.e("decodeBitmapFromBase64", "currentsize:"+decodedByte.getWidth()+"-"+decodedByte.getHeight()+",desire size:"+width +"-"+height);
		 return Bitmap.createScaledBitmap(decodedByte, width, height, true);
	}

	public static int convertDPToPixels(Context context, int dp) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		float fpixels = metrics.density * dp;
		int pixels = (int) (fpixels + 0.5f);
		return pixels;
	}
	
	public static void saveCacheWeather(Context context,Weather weather){
		if(context == null){
			return;
		}
		FileOutputStream fos=null;
		ObjectOutputStream os = null;
		try {
			fos = context.openFileOutput(Constants.CACHE_WEATHER_FILE, Context.MODE_PRIVATE);
			os = new ObjectOutputStream(fos);
			os.writeObject(weather);
			Log.e("Weather","Weather saved cached!");
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Weather getWeatherCache(Context context){
		FileInputStream fis=null;
		ObjectInputStream is=null;
		Weather cachedWeather = null;
		try {
			fis = context.openFileInput(Constants.CACHE_WEATHER_FILE);
			is = new ObjectInputStream(fis);
			cachedWeather = (Weather)is.readObject();
		} catch (FileNotFoundException e) {
//			e.printStackTrace();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is!=null)
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return cachedWeather;
	}
}
